import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/login.vue'
import Register from '@/views/register.vue'
import Layout from '@/views/layout.vue'
import Article from '@/views/article.vue'
import Collect from '@/views/collect.vue'
import Like from '@/views/like.vue'
import User from '@/views/user.vue'
import NotFound from '@/views/NotFound.vue'

import { getToken } from '@/utils/storage'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Layout,
    redirect: '/article',
    children: [
      { path: 'article', component: Article },
      { path: 'collect', component: Collect },
      { path: 'like', component: Like },
      { path: 'user', component: User }
    ]
  },
  { path: '/login', component: Login },
  { path: '/register', component: Register },
  { path: '*', component: NotFound }
]

const router = new VueRouter({
  routes
})

const token = getToken()
const whiteList = ['/login', '/register']

router.beforeEach((to, from, next) => {
  if (whiteList.includes(to.path)) {
    next()
  } else if (token) {
    next()
  } else {
    next('/login')
  }
})

export default router
